package client;
import java.awt.Frame;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JFrame;

import toolkit.Debug;
import toolkit.View;

public class TrayIcon implements ActionListener
{
	private boolean framesVisible = true;
	
	private java.awt.TrayIcon trayIcon;
	
	private PopupMenu popupMenu;
	
	private MenuItem itemClose;
	
	public TrayIcon()
	{
		if (SystemTray.isSupported())
		{
			trayIcon = new java.awt.TrayIcon(View.getIcon(), "Project Poker");
			trayIcon.setImageAutoSize(true);
			trayIcon.addMouseListener(mouseListener);
			
			popupMenu = new PopupMenu();
			trayIcon.setPopupMenu(popupMenu);
			
			itemClose = new MenuItem("Close");
			itemClose.addActionListener(this);
			popupMenu.add(itemClose);
			
			try
			{
				SystemTray.getSystemTray().add(trayIcon);
			}
			catch (Exception e)
			{
				Debug.log(e);
			}
		}
	}
	
	public PopupMenu getPopupMenu()
	{
		return popupMenu;
	}
	
	public void actionPerformed(ActionEvent e)
	{
		if (e.getSource() == itemClose)
		{
			Client.closeClient();
		}
	}
	
	private MouseListener mouseListener = new MouseAdapter()
	{
		public void mouseReleased(MouseEvent e)
		{
			if (e.getClickCount() >= 2)
			{
				framesVisible = !framesVisible;
				
				for (Frame frame: JFrame.getFrames())
				{
					if (frame instanceof JFrame && frame.isVisible())
					{
						frame.setExtendedState(framesVisible ? JFrame.NORMAL : JFrame.ICONIFIED);
					}
				}
			}
		}
	};
}
